//AudioUtils.ts
class AudioUtils {
  private async initAudioRenderer(param?: AudioParam): Promise<Media.AVPlayer> {
    try {
      let audioRendererInfo: Audio.AudioRendererInfo = {
        content: Audio.ContentType.CONTENT_TYPE_SONIFICATION,
        usage: Audio.StreamUsage.STREAM_USAGE_MEDIA,
        rendererFlags: 0
      };
      let audioMedia = await Media.createAVPlayer();
      if (CommonUtils.isInvalid(audioMedia)) {
        log.showWarn('audioMedia is null as createAVPlayer fail.');
        return undefined;
      }
      audioMedia.on('stateChange', async (state: string, reason: Media.StateChangeReason) => {
        switch (state) {
          case 'idle': // 成功调用reset接口后触发该状态机上报
            log.showDebug('AVPlayer state idle called.');
            audioMedia?.release(); // 调用release接口销毁实例对象
            break;
          case 'initialized': // avplayer 设置播放源后触发该状态上报
            log.showDebug('AVPlayer state initialized called.');
            if (audioMedia) {
              audioMedia.audioRendererInfo = audioRendererInfo;
            }
            audioMedia?.prepare();
            break;
          case 'prepared': // prepare调用成功后上报该状态机
            log.showDebug('AVPlayer state prepared called.');
            audioMedia?.play(); // 调用播放接口开始播放
            break;
          case 'playing': // play成功调用后触发该状态机上报
            log.showDebug('AVPlayer state playing called.');
            break;
          case 'paused': // pause成功调用后触发该状态机上报
            log.showDebug('AVPlayer state paused called.');
            audioMedia?.stop();
            break;
          case 'completed': // 播放结束后触发该状态机上报
            log.showDebug('AVPlayer state completed called.');
            audioMedia?.stop(); //调用播放结束接口
            break;
          case 'stopped': // stop接口成功调用后触发该状态机上报
            log.showDebug('AVPlayer state stopped called.');
            audioMedia?.reset(); // 调用reset接口初始化avplayer状态
            break;
          case 'released':
            log.showDebug('AVPlayer state released called.');
            param?.onRelease?.();
            break;
          default:
            log.showWarn('AVPlayer state unknown called.');
            break;
        }
      });
      audioMedia?.on('error', (error: BusinessError) => {
        log.error('play error:', error);
        audioMedia?.reset();
      });
      return audioMedia;
    } catch (error) {
      log.error('initAudioRenderer error', error);
    }
    return undefined;
  }
}
